import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sainbainu/common/enums/message_type.dart';
import 'package:sainbainu/common/models/response/message_num_response.dart';
import 'package:sainbainu/common/services/message.dart';

import 'index.dart';

class MessageController extends GetxController
    with GetSingleTickerProviderStateMixin {
  MessageController();

  final state = MessageState();

  Worker? worker;

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
    state.tabController = TabController(
      length: state.tabsList.length,
      vsync: this,
    );

    /// 切换 tabs 清空未读消息数量
    state.tabController.addListener(() async {
      if (!state.tabController.indexIsChanging) {
        await clearBadge(state.tabController.previousIndex);
      }
      await MessageService.to.getMessageNum();
    });

    /// 设置未读消息数量
    worker = ever(MessageService.to.messageNumResponse, (messageNumResponse) {
      setBadge(messageNumResponse);
    });
    setBadge(MessageService.to.messageNumResponse.value);
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
    state.tabController.dispose();
    worker?.dispose();
  }

  /// 清空未读消息数量
  Future<void> clearBadge(int previousIndex) async {
    MessageType msgType = MessageType.all;
    if (previousIndex == 0) {
      msgType = MessageType.likeCollec;
    } else if (previousIndex == 1) {
      msgType = MessageType.follow;
    } else if (previousIndex == 2) {
      msgType = MessageType.comment;
    }
    await MessageService.to.clearMessageNum(msgType);
  }

  /// 设置未读消息数量
  setBadge(MessageNumResponse messageNumResponse) {
    state.tabsList[0]['badge'] = messageNumResponse.operateNum.toString();
    state.tabsList[0]['showBadge'] = messageNumResponse.operateNum > 0;
    state.tabsList[1]['badge'] = messageNumResponse.followNum.toString();
    state.tabsList[1]['showBadge'] = messageNumResponse.followNum > 0;
    state.tabsList[2]['badge'] = messageNumResponse.commentNum.toString();
    state.tabsList[2]['showBadge'] = messageNumResponse.commentNum > 0;
    update(['tabs']);
  }
}
